package com.zbkj.front.controller.callback;

import com.zbkj.common.result.CommonResult;
import com.zbkj.service.monitor.channel.hemengyun.request.HeMengYunHelper;
import com.zbkj.service.service.monitor.IHeMengYunCallBackService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName: MonitorEquipmentCallBackController
 * @Description: TODO
 * @Author: 监控设备会调
 * @Date: 2024/1/12 22:26
 * @Version: V1.0
 **/
@RestController
@Api(tags = "监控设备回调")
@RequestMapping("/api/front/callback/monitor")
@Slf4j
public class MonitorEquipmentCallBackController {

    @Autowired
    private HeMengYunHelper heMengYunHelper;

    @Autowired
    private List<IHeMengYunCallBackService> heMengYunCallBackService;

    @PostMapping("/hemengyun/callBack")
    @ApiOperation("鹤梦云接口回调")
    public CommonResult callBack(HttpServletRequest request) {
//        log.info("#callBack#鹤梦云接口回调");

        StringBuilder requestBody = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                requestBody.append(line);
            }
        } catch (IOException e) {
            log.error("Error reading request body", e);
            return new CommonResult(-1, "Failed to read request body");
        }
        String data = heMengYunHelper.aesDecrypt(requestBody.toString());

        String action = request.getHeader("Action");
        //log.info("#callBack#鹤梦云接口回调Action:[{}];requestBody={};解密后数据={}", action, requestBody.toString(), data);

        heMengYunCallBackService.forEach(service -> service.callBack(action, data));

        return new CommonResult(0, "");
    }
}
